package ace.module.oauth2.server.core.impl.util;

import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;

/**
 * @author caspar
 * @date 2023/7/29 9:19
 */
public final class Oauth2AssertUtils {
  public static final String ERROR_URI =
      "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";

  public static void isTrue(boolean value, String msgTemplate, String... messages) {
    if (value) {
      OAuth2Error error =
          new OAuth2Error(
              OAuth2ErrorCodes.SERVER_ERROR, String.format(msgTemplate, messages), ERROR_URI);
      throw new OAuth2AuthenticationException(error);
    }
  }

  public static void isFalse(boolean value, String msgTemplate, String... messages) {
    isTrue(!value, msgTemplate, messages);
  }

  public static void isNull(Object value, String msgTemplate, String... messages) {
    isTrue(value == null, msgTemplate, messages);
  }

  public static void throwError(String errorCode, String parameterName, String errorUri) {
    OAuth2Error error =
        new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
    throw new OAuth2AuthenticationException(error);
  }
}
